package com.edu.dao.impl;

import com.edu.dao.BaseDao;
import com.edu.dao.productOrderDao;
import com.edu.entity.productOrder;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class productOrderDaoImpl implements productOrderDao {
	
    private BaseDao bd = new BaseDao();
    
    @Override
    public List<productOrder> getAll(int sellerId, int type) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<productOrder> orderList = new ArrayList<>();
        
        try {
            conn = bd.getConn();
            StringBuilder sql = new StringBuilder();
            
            if (type == 5) {
                // 只查询未生成订单的商品
                sql.append(
                    "SELECT " +
                    "  0 AS orderId, " +
                    "  g.goodnum AS stock, " +
                    "  g.goodimg AS goodImg, " +
                    "  g.goodname AS goodName, " +
                    "  g.gooddec AS goodDesc, " +
                    "  g.goodprice AS goodPrice, " +
                    "  NULL AS buyerName, " +
                    "  0 AS buyerId, " +
                    "  0 AS buyId, " +
                    "  g.goodid AS goodsId, " +
                    "  g.sellerid AS sellerId, " +
                    "  NULL AS orderTime, " +
                    "  '' AS packageNum, " +
                    "  NULL AS dispatchTime, " +
                    "  NULL AS receiveTime, " +
                    "  0 AS statusId, " +
                    "  NULL AS statusTime, " +
                    "  5 AS orderType, " +
                    "  NULL AS address " +
                    "FROM goods g " +
                    "WHERE g.sellerid = ? " +
                    "  AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.commodityId = g.goodid)"
                );
                ps = conn.prepareStatement(sql.toString());
                ps.setInt(1, sellerId);
            } else if (type == 0) {
                // 只查询有订单的商品
                sql.append(
                    "SELECT " +
                    "  po.orders_id AS orderId, " +
                    "  g.goodimg AS goodImg, " +
                    "  g.goodname AS goodName, " +
                    "  g.gooddec AS goodDesc, " +
                    "  g.goodprice AS goodPrice, " +
                    "  u.username AS buyerName, " +
                    "  u.userid AS buyerId, " + 
                    "  po.target_user_id AS buyId, " +
                    "  po.commodityId AS goodsId, " +
                    "  po.user_id AS sellerId, " +
                    "  po.datatime AS orderTime, " +
                    "  '' AS packageNum, " +
                    "  po.shipmentDate AS dispatchTime, " +
                    "  NULL AS receiveTime, " +
                    "  po.state AS statusId, " +
                    "  po.datatime AS statusTime, " +
                    "  po.state AS orderType, " +
                    "  CONCAT(a.Province, a.city, a.site, a.other) AS address " +
                    "FROM orders po " +
                    "JOIN goods g ON po.commodityId = g.goodid " +
                    "JOIN user u ON po.target_user_id = u.userid " +
                    "LEFT JOIN address a ON po.addressid = a.addressid " +
                    "WHERE po.user_id = ? " +
                    "ORDER BY po.datatime DESC"
                );
                ps = conn.prepareStatement(sql.toString());
                ps.setInt(1, sellerId);
            } else {
                // 原始订单查询（type=1,2,3,4）
                sql.append(
                    "SELECT " +
                    "  po.orders_id AS orderId, " +
                    "  g.goodimg AS goodImg, " +
                    "  g.goodname AS goodName, " +
                    "  g.gooddec AS goodDesc, " +
                    "  g.goodprice AS goodPrice, " +
                    "  u.username AS buyerName, " +
                    "  u.userid AS buyerId, " + 
                    "  po.target_user_id AS buyId, " +
                    "  po.commodityId AS goodsId, " +
                    "  po.user_id AS sellerId, " +
                    "  po.datatime AS orderTime, " +
                    "  '' AS packageNum, " +
                    "  po.shipmentDate AS dispatchTime, " +
                    "  NULL AS receiveTime, " +
                    "  po.state AS statusId, " +
                    "  po.datatime AS statusTime, " +
                    "  po.state AS orderType, " +
                    "  CONCAT(a.Province, a.city, a.site, a.other) AS address " +
                    "FROM orders po " +
                    "JOIN goods g ON po.commodityId = g.goodid " +
                    "JOIN user u ON po.target_user_id = u.userid " +
                    "LEFT JOIN address a ON po.addressid = a.addressid " +
                    "WHERE po.user_id = ? " +
                    " AND po.state = ?" +
                    " ORDER BY po.datatime DESC"
                );
                ps = conn.prepareStatement(sql.toString());
                ps.setInt(1, sellerId);
                ps.setInt(2, type);
            }
            
            rs = ps.executeQuery();
            while (rs.next()) {
                productOrder order = new productOrder();
                order.setOrderId(rs.getInt("orderId"));
                order.setGoodImg(rs.getString("goodImg"));
                order.setGoodName(rs.getString("goodName"));
                order.setGoodDesc(rs.getString("goodDesc"));
                order.setGoodPrice(rs.getDouble("goodPrice"));
                order.setBuyerName(rs.getString("buyerName"));
                order.setBuyerId(rs.getInt("buyerId"));
                order.setBuyId(rs.getInt("buyId"));
                order.setGoodsId(rs.getInt("goodsId"));
                order.setSellerId(rs.getInt("sellerId"));
                order.setOrderTime(rs.getTimestamp("orderTime"));
                order.setPackageNum(rs.getString("packageNum"));
                order.setDispatchTime(rs.getTimestamp("dispatchTime"));
                order.setReceiveTime(rs.getTimestamp("receiveTime"));
                order.setStatusId(rs.getInt("statusId"));
                order.setStatusTime(rs.getTimestamp("statusTime"));
                order.setOrderType(rs.getInt("orderType"));
                order.setAddress(rs.getString("address"));
                
                orderList.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            bd.closeAll(conn, ps, rs);
        }
        
        return orderList;
    }
    
    @Override
    public boolean cancelOrder(int orderId, int sellerId) {
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            conn = bd.getConn();
            // 检查订单是否存在且属于该商家
            String checkSql = "SELECT orders_id FROM orders WHERE orders_id = ? AND user_id = ?";
            ps = conn.prepareStatement(checkSql);
            ps.setInt(1, orderId);
            ps.setInt(2, sellerId);
            ResultSet rs = ps.executeQuery();
            
            if (!rs.next()) {
                return false;
            }
            
            if (ps != null) ps.close();
            
            // 更新订单状态为已取消 (3)
            String updateSql = "UPDATE orders SET state = ?, shipmentDate = ? WHERE orders_id = ?";
            ps = conn.prepareStatement(updateSql);
            ps.setInt(1, 3); // 已取消
            ps.setTimestamp(2, new Timestamp(System.currentTimeMillis())); // 使用当前时间
            ps.setInt(3, orderId);
            
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            bd.closeAll(conn, ps);
        }
    }
    
    @Override
    public boolean shipOrder(int orderId, int sellerId, String trackingNumber) {
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            conn = bd.getConn();
            // 检查订单是否存在且属于该商家
            String checkSql = "SELECT orders_id FROM orders WHERE orders_id = ? AND user_id = ?";
            ps = conn.prepareStatement(checkSql);
            ps.setInt(1, orderId);
            ps.setInt(2, sellerId);
            ResultSet rs = ps.executeQuery();
            
            if (!rs.next()) {
                return false;
            }
            
            if (ps != null) ps.close();
            
            // 更新发货时间和订单状态 (2 = 待发货)
            String updateSql = "UPDATE orders SET state = 5, shipmentDate = ? WHERE orders_id = ?";
            ps = conn.prepareStatement(updateSql);
            ps.setTimestamp(1, new Timestamp(System.currentTimeMillis())); // 发货时间
            ps.setInt(2, orderId);
            
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            bd.closeAll(conn, ps);
        }
    }

    @Override
    public boolean offShelf(int goodsid) {
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            // 获取数据库连接
            conn = bd.getConn();
            
            String sql = "UPDATE goods SET goodonsellstat = ? WHERE goodid = ?";
            ps = conn.prepareStatement(sql);
            
            // 设置参数
            ps.setInt(1, -1);  // 设置状态为-1（下架）
            ps.setInt(2, goodsid);  // 设置商品ID
            
            // 执行更新
            int affectedRows = ps.executeUpdate();
            
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 关闭资源（使用BaseDao的closeAll方法）
            bd.closeAll(conn, ps);
        }
    }
    public boolean offShelfgoods(int goodsid, int sellerId) {
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            conn = bd.getConn();
            // 添加卖家ID验证和订单状态检查
            String sql = "DELETE FROM goods " +
                         "WHERE goodid = ? " +
                         "AND sellerid = ? " ;
            ps = conn.prepareStatement(sql);
            ps.setInt(1, goodsid);
            ps.setInt(2, sellerId);
            
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            bd.closeAll(conn, ps);
        }
    }
}